package com.mmlc.meimei.lichengkongjian;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.LogUtils;
import com.mmlc.inter.InterActivity;
import com.mmlc.network.filter.UploadImgRequestFilter;
import com.mmlc.network.filter.WgRequestFilter;
import com.mmlc.network.responsebean.GoodsDetailResponseBean;
import com.mmlc.utils.ImageTools;
import com.mmlc.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class WgEditeActivity extends InterActivity {

    EditText pp,cm,jg;
    RelativeLayout rr_a,rr_b,rr_c,rr_d;
    ImageView iv_a,iv_b,iv_c,iv_d,iv_post;
    @Override
    protected int initContentView() {
        return R.layout.activity_wg_edite;
    }

    @Override
    protected void initView() {
        rr_a= (RelativeLayout) findViewById(R.id.rr_a);
        rr_b= (RelativeLayout) findViewById(R.id.rr_b);
        rr_c= (RelativeLayout) findViewById(R.id.rr_c);
        rr_d= (RelativeLayout) findViewById(R.id.rr_d);
        iv_a= (ImageView) findViewById(R.id.iv_a);
        iv_b= (ImageView) findViewById(R.id.iv_b);
        iv_c= (ImageView) findViewById(R.id.iv_c);
        iv_d= (ImageView) findViewById(R.id.iv_d);
        iv_post= (ImageView) findViewById(R.id.iv_post);
        findViewById(R.id.iva_delete).setOnClickListener(this);
        findViewById(R.id.ivb_delete).setOnClickListener(this);
        findViewById(R.id.ivc_delete).setOnClickListener(this);
        findViewById(R.id.ivd_delete).setOnClickListener(this);
        findViewById(R.id.iv_post).setOnClickListener(this);
        findViewById(R.id.tv_submit).setOnClickListener(this);
        findViewById(R.id.iv_set).setVisibility(View.GONE);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });;
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("我购");
       pp= (EditText) findViewById(R.id.pp);
       cm= (EditText) findViewById(R.id.cm);
       jg= (EditText) findViewById(R.id.jg);
        img_list.add(iv_a);
        img_list.add(iv_b);
        img_list.add(iv_c);
        img_list.add(iv_d);

        rr_list.add(rr_a);
        rr_list.add(rr_b);
        rr_list.add(rr_c);
        rr_list.add(rr_d);
    }
    private HashMap<RelativeLayout,String> picPath_list=new HashMap<>();
    private HashMap<RelativeLayout,String> picMap=new HashMap<>();
    private ArrayList<ImageView> img_list = new ArrayList<>();
    private ArrayList<RelativeLayout> rr_list = new ArrayList<>();
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.iva_delete:
                rr_a.setVisibility(View.GONE);
                picPath_list.remove(rr_a);
                picMap.remove(rr_a);
                img_list.add(iv_a);
                rr_list.add(rr_a);
                break;
            case R.id.ivb_delete:
                rr_b.setVisibility(View.GONE);
                picPath_list.remove(rr_b);
                picMap.remove(rr_b);
                img_list.add(iv_b);
                rr_list.add(rr_b);
                break;
            case R.id.ivc_delete:
                rr_c.setVisibility(View.GONE);
                picPath_list.remove(rr_c);
                picMap.remove(rr_c);
                img_list.add(iv_c);
                rr_list.add(rr_c);
                break;
            case R.id.ivd_delete:
                rr_d.setVisibility(View.GONE);
                picPath_list.remove(rr_d);
                picMap.remove(rr_d);
                img_list.add(iv_d);
                rr_list.add(rr_d);
                iv_post.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_post:
                imageSelector(4-picPath_list.size());
                break;
            case R.id.tv_submit:
                time = 0;
                stringBuffer = new StringBuffer();

                if(TextUtils.isEmpty(pp.getText().toString().trim())){
                    ToastUtils.showToast("请输入品牌");
                    return;
                }
                if(TextUtils.isEmpty(cm.getText().toString().trim())){
                    ToastUtils.showToast("请输入尺码");
                    return;
                }
                if(TextUtils.isEmpty(jg.getText().toString().trim())){
                    ToastUtils.showToast("请输入价格");
                    return;
                }
                if(!App.user.getLoginState()){
                    ToastUtils.showToast("请先登录");
                    return;
                }

                //提交举报信息
                submitReport();
                break;
        }
        if(picPath_list.size()<4){
            iv_post.setVisibility(View.VISIBLE);
        }
    }

    public Handler mHandler;

    private void submitReport() {
        //handler用于处理图片上传是否完成
        mHandler = new Handler(){
            public int i=0;
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0){
                    i++;
                    if(i == picMap.size()){
                        commitInfo(new String(stringBuffer));
                    }
                }
            }
        };
        final String str ="";
        if(picMap.size()!=0){
            for (String v : picMap.values()) {
                //先上传图片
                commitPhoto(v);
                //再获取服务器返回的图片地址
            }
        }else {
            commitInfo(str);
        }

    }

    private void commitInfo(String str) {
        final WgRequestFilter filter=new WgRequestFilter(this);
        filter.requestBean.imgs=str;
        filter.requestBean.brand_name=pp.getText().toString().trim();
        filter.requestBean.price=jg.getText().toString().trim();
        filter.requestBean.size=cm.getText().toString().trim();
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<GoodsDetailResponseBean>() {
            @Override
            public void onSuccess(GoodsDetailResponseBean result) {
                if(result.getCode()==0){
                    startActivity(new Intent(context,WGActivity.class));
                    finish();
                }else{
                    ToastUtils.showToast(result.getMessage());
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });
    }

    public  int time=0;
    private void commitPhoto(final String tmpheader) {
        UploadImgRequestFilter imgFilter = new UploadImgRequestFilter((BaseParentActivity)activity);
        imgFilter.requestParams.addBodyParameter("imgFile", new File(tmpheader));
        imgFilter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e(TAG, "onSuccess: "+result );
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject data = jsonObject.getJSONObject("data");
                    stringBuffer.append(data.optString("path")+",");
                    mHandler.sendEmptyMessage(0);
                    time++;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess.toString());
            }
        });
    }
    public StringBuffer stringBuffer = new StringBuffer();
    public static final int REQUEST_IMAGE =100;
    private void imageSelector(int picnums) {
        ArrayList<String> defaultDataArray =  new ArrayList<>();
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, picnums);
        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择图片,回填选项(支持String ArrayList)
        intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
        startActivityForResult(intent, REQUEST_IMAGE);
    }
    //照片缩小的比例
    private static final int SCALE = 2;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.e("onActivityResult","------"+requestCode+"----"+requestCode);

        if(requestCode == REQUEST_IMAGE&& resultCode ==RESULT_OK && data!=null){
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            ContentResolver contentResolver = getContentResolver();
            int currentLen = picPath_list.size();
            for (int i = 0; i < path.size(); i++) {
                LogUtils.e("选择的图片uri", path.get(i));
                Bitmap bitmap = BitmapFactory.decodeFile(path.get(i));
                if (bitmap != null) {
                    Bitmap smallBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
                    bitmap.recycle();
                    img_list.get(i).setImageBitmap(smallBitmap);
                    rr_list.get(i).setVisibility(View.VISIBLE);
                    //将处理过的图片保存到本地
                    String currentHeadPhoto = ImageTools.savePhotoToSDCard(smallBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()));
                    picPath_list.put(rr_list.get(i),currentHeadPhoto);
                    picMap.put(rr_list.get(i),currentHeadPhoto);
                }
            }
            for (int i = 0; i < path.size(); i++) {
                img_list.remove(0);
                rr_list.remove(0);
            }
            if (picPath_list.size()==4){
                iv_post.setVisibility(View.GONE);
            }
        }
    }
}
